Paul's JavaScript Examples    
 
Validating a date entered by the user

This simple Javascript routine checks if a date entered conforms to the mm/dd/yy (eg. 12/18/98) specification and will return an error message with a suggestion as to what may be wrong to the user.

Example

Please use the 12/18/98 type format.

Please enter a date: Usage

<INPUT TYPE="TEXT" NAME="mydate" VALUE="" SIZE="8" MAXLENGTH="8" onChange="Check_Date(this.value)">

Source

<SCRIPT LANGUAGE="javascript">
<!--
function Check_Date(item)
{
        var returnVal = false

        checkVal = 0

        if (item.length < 8)
        {
           checkVal = 1
        }
        else
        {
           if (item.substring(2,3) != '/' || item.substring(5,6) != '/')
           {
              checkVal = 2
           }
           if (isNaN(parseInt(item.substring(0,2))) || parseInt(item.substring(0,2)) < 1 || parseInt(item.substring(0,2)) > 12)
           {
              checkVal = 3
           }
           if (isNaN(parseInt(item.substring(3,5))) || parseInt(item.substring(3,5)) < 1 || parseInt(item.substring(3,5)) > 31)
           {
              checkVal = 4
           }
           if (isNaN(parseInt(item.substring(6,8))) || parseInt(item.substring(6,8)) < 0 || parseInt(item.substring(6,8)) > 99)
           {
              checkVal = 5
           }
        }    
        if (checkVal == 0) returnVal = true
        if (checkVal == 1) fout = 'Date apparently not filled in according\nto specifications.'
        if (checkVal == 2) fout = 'Day format to use is mm/dd/yy. Where\nmm = month eg. \'07\'dd = day eg. \'01\' and\nyy is year eg \'75\''
        if (checkVal == 3) fout = 'Incorrect entry of month, value should be 01 to 12'
        if (checkVal == 4) fout = 'Incorrect entry of day, figure should be 01 - 31' 
        if (checkVal == 5) fout = 'Incorrect entry of year, figure should be 00 - 99' 
       
        if (returnVal == false)
        {
                alert('Your date entry appears incorrect!\n \nError Report:\n' + fout)
        }
        return returnVal
}
// -->
</SCRIPT>